﻿using System;
using System.Reactive.Disposables;
using ExcelDna.Integration;

namespace Cubicle.Excel.Functions
{
    class ExcelObjectHandle : IExcelObservable //, IDisposable
    {
        readonly object _returnValue;
        readonly Action<object> _onDispose;

        public ExcelObjectHandle(object returnValue, Action<object> onDispose)
        {
            _returnValue = returnValue;
            _onDispose = onDispose;
        }

        // We expect to be called only once, ever
        public IDisposable Subscribe(IExcelObserver observer)
        {
            observer.OnNext(_returnValue);
            return Disposable.Create(() => _onDispose(_returnValue));
        }

        // public void Dispose()
        // {
        //    Alternative implementation could Dispose here, and return "this" from the subscription....?
        //}

        public static object CreateHandle(string callerFunctionName, object callerParameters, ExcelFunc getReturnValue, Action<object> onDispose)
        {
            return ExcelAsyncUtil.Observe(callerFunctionName, callerParameters, () =>
                                                                                new ExcelObjectHandle(getReturnValue(), onDispose));
        }
    }
}